<template>
   <div style="height: 600px;">
      <!-- 动态查询 -->
      <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
         <el-form-item label="考试类型" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入考试类型" clearable style="width: 220px"
               @keyup.enter="handleQuery" />
         </el-form-item>

         <el-form-item label="课程" prop="subId">
            <el-cascader v-model="queryParams.subId" :options="options5" clearable style="width: 220px"
               @keyup.enter="handleQuery" />
         </el-form-item>
         <el-form-item label="发布人" prop="uid">
            <el-select v-model="queryParams.uid" placeholder="请选择发布人" clearable style="width: 220px">
               <el-option v-for="dict in options1" :key="dict.userId" :label="dict.nickname" :value="dict.userId" />
            </el-select>
         </el-form-item>
         <el-form-item label="班级名称" style="font-weight: 800;" prop="classId">
            <el-tree-select accordion="true" v-model="queryParams.classId" clearable
               :props="{ label: 'name', children: 'children', value: 'classId' }" :data="cacheData"
               style="width: 220px" />
         </el-form-item>
         <el-form-item label="发布时间" prop="beginTime">
            <el-date-picker v-model="queryParams.beginTime" type="datetime" placeholder="请选择开始时间"
               format="YYYY/MM/DD hh:mm:ss" value-format="x" />
         </el-form-item>

         <el-form-item label="" prop="endTime">
            <el-date-picker v-model="queryParams.endTime" type="datetime" placeholder="请选择结束时间"
               format="YYYY/MM/DD hh:mm:ss" value-format="x" />
         </el-form-item>
         <el-form-item label="申请状态" prop="state">
            <el-select v-model="queryParams.state" placeholder="申请状态" clearable style="width: 240px">
               <el-option v-for="dict in optionsStatus" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
         </el-form-item>
         <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
         </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
               v-hasPermi="['system:role:add']">新增</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
               v-hasPermi="['system:role:edit']">修改</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
               v-hasPermi="['system:role:remove']">删除</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
               v-hasPermi="['system:role:export']">导出</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleTeachingcycle" v-hasPermi="['system:role:export']"
               v-if="user.roles.roleName === '管理员'">发布日考</el-button>
         </el-col>
         <el-row style="margin-left: 54%;">
            <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top"
               v-if="search">
               <el-button circle icon="Search" @click="toggleSearch()" />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="刷新" placement="top">
               <el-button circle icon="Refresh" @click="refresh()" />
            </el-tooltip>
         </el-row>
      </el-row>

      <!-- 表格数据 -->
      <el-table v-loading="loading" :data="filterTableData" @selection-change="handleSelectionChange"
         :header-cell-style="{ background: '#eee', color: '#909399' }">
         <template #empty v-if="filterTableData.length === 0">
            <el-empty description="暂无数据" style="margin-top: 10%;" />
         </template>
         <el-table-column type="selection" width="55" align="center" />
         <el-table-column label="考试信息编号" type="index" width="108" />
         <el-table-column label="考试类型" prop="name" :show-overflow-tooltip="true" width="80" />
         <el-table-column label="发布人" prop="tuser.nickname" :show-overflow-tooltip="true" width="70" />
         <el-table-column label="课程" prop="ssubject.subjectName" :show-overflow-tooltip="true" width="60" />
         <el-table-column label="单选题数量" prop="radioCount" :show-overflow-tooltip="true" width="95" />
         <el-table-column label="多选题数量" prop="checkCount" :show-overflow-tooltip="true" width="95" />
         <el-table-column label="判断题数量" prop="judgmentCount" :show-overflow-tooltip="true" width="95" />
         <el-table-column label="简答题数量" prop="textCount" :show-overflow-tooltip="true" width="95" />
         <el-table-column label="班级" prop="sclass.className" :show-overflow-tooltip="true" width="55" />
         <el-table-column label="开始时间" prop="beginTime" :show-overflow-tooltip="true" width="90" />
         <el-table-column label="结束时间" prop="endTime" :show-overflow-tooltip="true" width="90" />
         <el-table-column label="考试时长" prop="examDuration" :show-overflow-tooltip="true" width="90" />
         <el-table-column label="状态" :show-overflow-tooltip="true" width="90">
            <template #default="scope">
               <el-tag size="small" v-if="scope.row.state == 0" plain round type="success">待开始</el-tag>
               <el-tag size="small" v-else-if="scope.row.state == 1" plain round type="primary">考试中</el-tag>
               <el-tag size="small" v-else-if="scope.row.state == 2" plain round type="warning">已结束</el-tag>
               <el-tag size="small" v-else-if="scope.row.state == 3" plain round type="info">待审核</el-tag>
               <el-tag size="small" v-else-if="scope.row.state == 4" plain round type="danger">被驳回</el-tag>
            </template>
         </el-table-column>
         <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
               <el-tooltip content="修改" placement="top"
                  v-if="scope.row.state === 0 && scope.row.state !== 3 && scope.row.state !== 4">
                  <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
               </el-tooltip>
               <el-tooltip content="删除" placement="top"
                  v-if="scope.row.state !== 1 && scope.row.state !== 3 && scope.row.state !== 4">
                  <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
               </el-tooltip>
               <el-tooltip content="查看试卷" placement="top"
                  v-if="user.roles.roleName === '管理员' && scope.row.state !== 3 && scope.row.state !== 4">
                  <el-button link type="primary" icon="Collection" @click="handleAuthUser(scope.row)"></el-button>
               </el-tooltip>
               <el-tooltip content="补考" placement="top"
                  v-if="user.roles.roleName === '讲师' && scope.row.state === 2 && scope.row.state !== 3 && scope.row.state !== 4">
                  <el-button link type="primary" icon="Management" @click="handleMakeUp(scope.row)"></el-button>
               </el-tooltip>
               <el-tooltip content="同意申请" placement="top" v-if="user.roles.roleName === '管理员' && scope.row.state === 3">
                  <el-button link type="primary" icon="Check" @click="handleOk(scope.row)"></el-button>
               </el-tooltip>
               <el-tooltip content="驳回" placement="top" v-if="user.roles.roleName === '管理员' && scope.row.state === 3">
                  <el-button link type="primary" icon="Close" @click="handleReject(scope.row)"></el-button>
               </el-tooltip>
               <el-tooltip content="查询驳回原因" placement="top" v-if="scope.row.state === 4">
                  <el-button link type="primary" icon="View" @click="handleView(scope.row)"></el-button>
               </el-tooltip>
            </template>
         </el-table-column>
      </el-table>
   </div>
   <el-pagination background v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
      :page-sizes="[10, 15, 20, 25]" layout="total, sizes, prev, pager, next, jumper" :total="total"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" />

   <!-- 添加或修改考试对话框 -->
   <el-dialog :title="title" v-model="open" width="650px" append-to-body style="font-weight: 800;text-align: center;">
      <el-segmented v-model="boo" :options="['随机出题', '选择出题']" style="margin-left: -5%;" v-show="boolsUpdate" />
      <div v-if="boo == '随机出题'">
         <el-form ref="roleRef" :model="form" :rules="rules">
            <el-row>
               <el-col :span="12">
                  <el-form-item label="考 试" prop="name" style="margin-top: 10px;">
                     <el-input v-model="form.name" placeholder="请输入考试名称" clearable style="width: 230px" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="班级名称" prop="classId" style="margin-top: 10px;">
                     <el-tree-select accordion="true" v-model="form.classId"
                        :props="{ label: 'name', children: 'children', value: 'classId' }" :data="cacheData"
                        style="width: 160px;" />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row style="margin-top: 1%;">
               <el-col :span="12">
                  <el-form-item label="考试时间" style="width: 547px"
                     :rules="{ required: true, message: '考试时间不能为空', trigger: 'blur' }">
                     <el-date-picker v-model="ExamTime" value-format="YYYY-MM-DD HH:mm:ss" type="datetimerange"
                        range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间">
                     </el-date-picker>
                  </el-form-item>
               </el-col>
            </el-row>

            <el-form-item label="单 元" prop="subId">
               <el-select v-model="levelId" placeholder="请选择阶段" clearable style="width: 155px" @change="byId1(levelId)">
                  <el-option v-for="item in options2" :key="item.id" :label="item.levelName" :value="item.id" />
               </el-select>
               <el-select v-model="lpId" placeholder="请选择学习阶段" clearable style="width: 155px" @change="byId(lpId)">
                  <el-option v-for="dict in options4" :key="dict.id" :label="dict.name" :value="dict.id" />
                  <template #empty>
                     <span style="color: red;">请先选择一个阶段哦~</span>
                  </template>
               </el-select>
               <el-select v-model="form.subId" placeholder="请选择单元" clearable style="width: 155px">
                  <el-option v-for="dict in options3" :key="dict.id" :label="dict.subjectName" :value="dict.id" />
                  <template #empty>
                     <span style="color: red;">请先选择一个学习阶段哦~</span>
                  </template>
               </el-select>
               <el-tooltip class="box-item" effect="dark" content="选择对应的单元，进行出题" placement="top-start">
                  <el-icon style="color: #409EFF;padding-left: 10px;" size="180%">
                     <QuestionFilled />
                  </el-icon>
               </el-tooltip>
            </el-form-item>


            <el-row style="margin-top: 1%;">
               <el-col :span="12">
                  <el-form-item label="单选题数量" prop="radioCounts">
                     <el-input-number :min="0" :max="30" v-model="form.radioCounts" clearable style="width: 160px" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="分 值 :" prop="radioScope">
                     <el-input-number :min="0" :max="10" v-model="form.radioScope" clearable style="width: 160px" />
                     <el-tooltip class="box-item" effect="dark" content="请输入要考试的单选题分数" placement="top-start">
                        <el-icon style="color: #409EFF;padding-left: 10px;" size="180%">
                           <QuestionFilled />
                        </el-icon>
                     </el-tooltip>
                  </el-form-item>
               </el-col>
            </el-row>

            <el-row style="margin-top: 15px;">
               <el-col :span="12">
                  <el-form-item label="多选题数量" prop="checkCounts">
                     <el-input-number :min="0" :max="30" v-model="form.checkCounts" clearable style="width: 160px" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="分 值 :" prop="checkScope">
                     <el-input-number :min="0" :max="10" v-model="form.checkScope" clearable style="width: 160px" />
                     <el-tooltip class="box-item" effect="dark" content="请输入要考试的多选题分数" placement="top-start">
                        <el-icon style="color: #409EFF;padding-left: 10px;" size="180%">
                           <QuestionFilled />
                        </el-icon>
                     </el-tooltip>
                  </el-form-item>
               </el-col>
            </el-row>

            <el-row style="margin-top: 15px;">
               <el-col :span="12">
                  <el-form-item label="判断题数量" prop="judgmentCounts">
                     <el-input-number :min="0" :max="30" v-model="form.judgmentCounts" clearable style="width: 160px" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="分 值 :" prop="judgmentScope">
                     <el-input-number :min="0" :max="30" v-model="form.judgmentScope" clearable style="width: 160px" />
                     <el-tooltip class="box-item" effect="dark" content="请输入要考试的判断题分数" placement="top-start">
                        <el-icon style="color: #409EFF;padding-left: 10px;" size="180%">
                           <QuestionFilled />
                        </el-icon>
                     </el-tooltip>
                  </el-form-item>
               </el-col>
            </el-row>

            <el-row style="margin-top: 15px;">
               <el-col :span="12">
                  <el-form-item label="简单题数量" prop="textCounts">
                     <el-input-number :min="0" :max="30" v-model="form.textCounts" clearable style="width: 160px" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="分 值 :" prop="textScope">
                     <el-input-number :min="0" :max="30" v-model="form.textScope" clearable style="width: 160px" />
                     <el-tooltip class="box-item" effect="dark" content="请输入要考试的简单题分数" placement="top-start">
                        <el-icon style="color: #409EFF;padding-left: 10px;" size="180%">
                           <QuestionFilled />
                        </el-icon>
                     </el-tooltip>
                  </el-form-item>
               </el-col>
            </el-row>
         </el-form>
         <div class="dialog-footer" style="text-align: right;">
            <el-button type="primary" @click="submitForm">发 布</el-button>
            <el-button @click="cancel">取 消</el-button>
         </div>
      </div>
      <div v-else>
         <el-form ref="roleRef1" :model="form1" :rules="rules1">
            <el-row>
               <el-col :span="12">
                  <el-form-item label="考 试" prop="name" style="margin-top: 10px;">
                     <el-input v-model="form1.name" placeholder="请输入考试名称" clearable style="width: 230px" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="班级名称" prop="classId" style="margin-top: 10px;">
                     <el-tree-select accordion="true" v-model="form1.classId"
                        :props="{ label: 'name', children: 'children', value: 'classId' }" :data="cacheData"
                        style="width: 160px;" />
                  </el-form-item>
               </el-col>
            </el-row>

            <el-row style="margin-top: 1%;">
               <el-col :span="12">
                  <el-form-item label="考试时间" style="width: 547px"
                     :rules="{ required: true, message: '考试时间不能为空', trigger: 'blur' }">
                     <el-date-picker v-model="ExamTime" value-format="YYYY-MM-DD HH:mm:ss" type="datetimerange"
                        range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间">
                     </el-date-picker>
                  </el-form-item>
               </el-col>
            </el-row>

            <el-form-item label="单 元" prop="subId">
               <el-select v-model="levelId" placeholder="请选择阶段" clearable style="width: 155px" @change="byId1(levelId)">
                  <el-option v-for="item in options2" :key="item.id" :label="item.levelName" :value="item.id" />
               </el-select>
               <el-select v-model="lpId" placeholder="请选择学习阶段" clearable style="width: 155px" @change="byId(lpId)">
                  <el-option v-for="dict in options4" :key="dict.id" :label="dict.name" :value="dict.id" />
                  <template #empty>
                     <span style="color: red;">请先选择一个阶段哦~</span>
                  </template>
               </el-select>
               <el-select v-model="form1.subId" placeholder="请选择单元" clearable style="width: 155px"
                  @change="byId2(form1.subId)">
                  <el-option v-for="dict in options3" :key="dict.id" :label="dict.subjectName" :value="dict.id" />
                  <template #empty>
                     <span style="color: red;">请先选择一个学习阶段哦~</span>
                  </template>
               </el-select>
               <el-tooltip class="box-item" effect="dark" content="选择对应的单元，进行出题" placement="top-start">
                  <el-icon style="color: #409EFF;padding-left: 10px;" size="180%">
                     <QuestionFilled />
                  </el-icon>
               </el-tooltip>
            </el-form-item>

            <el-row style="margin-top: 15px;">
               <el-col :span="12">
                  <el-form-item label="单选题" prop="radioCounts">
                     <el-button @click="handleXun(1)" icon="Plus">选择</el-button>
                     <span v-show="flag1" style="margin-left: 20%;">数 量 : {{ text1 }}</span>
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="分 值 :" prop="radioScope">
                     <el-input-number :min="0" :max="10" v-model="form1.radioScope" clearable style="width: 160px" />
                     <el-tooltip class="box-item" effect="dark" content="请输入要考试的单选题分数" placement="top-start">
                        <el-icon style="color: #409EFF;padding-left: 10px;" size="180%">
                           <QuestionFilled />
                        </el-icon>
                     </el-tooltip>
                  </el-form-item>
               </el-col>
            </el-row>

            <el-row style="margin-top: 15px;">
               <el-col :span="12">
                  <el-form-item label="多选题" prop="checkCounts">
                     <el-button @click="handleXun(2)" icon="Plus">选择</el-button>
                     <span v-show="flag2" style="margin-left: 20%;">数 量 : {{ text2 }}</span>
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="分 值 :" prop="checkScope">
                     <el-input-number :min="0" :max="10" v-model="form1.checkScope" clearable style="width: 160px" />
                     <el-tooltip class="box-item" effect="dark" content="请输入要考试的多选题分数" placement="top-start">
                        <el-icon style="color: #409EFF;padding-left: 10px;" size="180%">
                           <QuestionFilled />
                        </el-icon>
                     </el-tooltip>
                  </el-form-item>
               </el-col>
            </el-row>

            <el-row style="margin-top: 15px;">
               <el-col :span="12">
                  <el-form-item label="判断题" prop="judgmentCounts">
                     <el-button @click="handleXun(3)" icon="Plus">选择</el-button>
                     <span v-show="flag3" style="margin-left: 20%;">数 量 : {{ text3 }}</span>
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="分 值 :" prop="judgmentScope">
                     <el-input-number :min="0" :max="30" v-model="form1.judgmentScope" clearable style="width: 160px" />
                     <el-tooltip class="box-item" effect="dark" content="请输入要考试的判断题分数" placement="top-start">
                        <el-icon style="color: #409EFF;padding-left: 10px;" size="180%">
                           <QuestionFilled />
                        </el-icon>
                     </el-tooltip>
                  </el-form-item>
               </el-col>
            </el-row>

            <el-row style="margin-top: 15px;">
               <el-col :span="12">
                  <el-form-item label="简单题" prop="textCounts">
                     <el-button @click="handleXun(4)" icon="Plus">选择</el-button>
                     <span v-show="flag4" style="margin-left: 20%;">数 量 : {{ text4 }}</span>
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="分 值 :" prop="textScope">
                     <el-input-number :min="0" :max="30" v-model="form1.textScope" clearable style="width: 160px" />
                     <el-tooltip class="box-item" effect="dark" content="请输入要考试的简单题分数" placement="top-start">
                        <el-icon style="color: #409EFF;padding-left: 10px;" size="180%">
                           <QuestionFilled />
                        </el-icon>
                     </el-tooltip>
                  </el-form-item>
               </el-col>
            </el-row>
         </el-form>
         <div>
            <div class="dialog-footer" style="text-align: right;">
               <el-button type="primary" @click="submitForm1">发 布</el-button>
               <el-button @click="cancel1">取 消</el-button>
            </div>
         </div>
      </div>
   </el-dialog>
   <el-dialog v-model="dialogVisibleXun" title="题目预览" width="800">
      <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="Add" v-show="bools1">确定选择</el-button>
            <el-button type="primary" plain icon="Plus" @click="addSubject()" v-show="bools">确定添加</el-button>
         </el-col>
      </el-row>
      <el-table ref="multipleTable" @selection-change="handleSelectionChange1" v-loading="loading" :data="tableData1"
         style="width: 100%;height: 575px;">
         <el-table-column type="selection" width="55" />
         <el-table-column label="试题编号" prop="id" width="110" />
         <el-table-column label="题型" width="120">
            <template #default="scope">
               <span v-if="scope.row.typeId == 1">单选题</span>
               <span v-if="scope.row.typeId == 2">多选题</span>
               <span v-if="scope.row.typeId == 3">判断题</span>
               <span v-if="scope.row.typeId == 4">简答题</span>
            </template>
         </el-table-column>
         <el-table-column label="题干" prop="question" width="280">
            <template #default="scope">
               <span class="answer-text">{{ scope.row.question.split("/")[0] }}</span>
            </template>
         </el-table-column>
         <el-table-column label="答案" width="350px">
            <template #default="scope">
               <span style="width: 300px;" class="answer-text">{{ scope.row.answerTxt }}</span>
            </template>
         </el-table-column>
      </el-table>
   </el-dialog>
   <!-- 查看题目 -->
   <el-dialog v-model="dialogVisible" :visible.sync="optionsQuestion" title="题目预览" width="800"
      :before-close="handleClose" :fullscreen="true">
      <!-- 页面内容 -->
      <p style="text-align: center;">
         <el-text style="font-size: 40px;font-weight: 600;color: black;">
            {{ name }}
         </el-text>
      </p>
      <p style="margin-left: 70%;color: black;font-weight: 500;">
         <el-text style="font-size: 20px;">
            考试时长 : {{ examDuration }}
         </el-text>
      </p>
      <div ref="containerRef"
         style="width: 79%;height: 635px;display: inline-block;overflow-y: auto;-ms-overflow-style: none;scrollbar-width: none;overflow: scroll;">
         <el-card :id="'part' + item.id" v-for="(item, index) in optionsQuestion"
            :body-style="{ padding: item.typeId == 3 || item.typeId == 4 ? '0px' : '20px' }"
            style="margin-bottom: 15px;">
            <template #header>
               <div class="card-header">
                  <span style="display: inline-block;width: 950px;">{{ index + 1 + ". " +
                     item.question.split("/")[0] }}</span>
                  <span style="position: relative;right: 0px;">{{ "(" + (item.typeId == 1 ? '单选题' : item.typeId == 2 ?
                     '多选题' : item.typeId == 3 ? '判断题' : item.typeId == 4 ? '简答题' : null) + ")" }}</span>
                  <el-tooltip content="删除该题" placement="top" v-if="obj.state === 0">
                     <el-button link type="primary" icon="Close" @click="subjectDelete(item.id)"
                        v-hasPermi="['system:user:resetPwd']"
                        style="position: relative; top: 0px;left: 100px;"></el-button>
                  </el-tooltip>
               </div>
            </template>

            <p style="margin-top: 10px;" v-if="item.typeId == 1"
               :style="{ color: item.answerTxt == 'A' && i == 0 ? 'red' : item.answerTxt == 'B' && i == 1 ? 'red' : item.answerTxt == 'C' && i == 2 ? 'red' : item.answerTxt == 'D' && i == 3 ? 'red' : 'BLACK' }"
               v-for="(text, i) in item.question.split('/')[1].split('_')" class="text item">{{ text }}</p>
            <p v-if="item.typeId == 2" :style="{ color: getColor(item.answerTxt, i) ? 'red' : 'black' }"
               v-for="(text, i) in item.question.split('/')[1].split('_')" class="text item">{{ text }}</p>
            <template #footer>答案：<span :style="{ color: item.typeId == 3 && item.answerTxt ? 'green' : 'red' }">{{
               item.answerTxt
            }}</span></template>
         </el-card>
         <el-card style="margin-bottom: 15px;height: 40%;" v-if="obj.state === 0">
            <el-tooltip content="添加题目" placement="top">
               <el-button link type="primary" size="" icon="Plus" @click="subjectAdd()" class="icon-large-button"
                  style="margin-left: 48%;margin-top: 5%;"></el-button>
            </el-tooltip>
         </el-card>
      </div>
      <div
         style="width: 20%;display: inline-block;height: 635px;overflow-y: auto;-ms-overflow-style: none;scrollbar-width: none;overflow: scroll;">
         <el-anchor style="height: 600px;" :container="containerRef" direction="vertical" type="horizontal"
            :offset="238" @click="handleClick">
            <el-anchor-link v-for="(item, index) in optionsQuestion" style="size: 20px;" :href="'#part' + item.id"
               :title="index + 1 + '.' + item.question.split('/')[0]" />
         </el-anchor>
      </div>
   </el-dialog>
   <!-- 教学周期日考弹框 -->
   <el-dialog v-model="teacherCycl" title="教学周期日考" width="600px" style="font-weight: 800;">
      <el-form :model="adTeacherCycl">
         <el-form-item label="教学周期" style="width: 90%;"
            :rules="{ required: true, message: '补考时间不能为空', trigger: 'blur' }">
            <el-date-picker v-model="adTeacherCycl.cycleTime" value-format="YYYY-MM-DD" type="daterange"
               range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间">
            </el-date-picker>
         </el-form-item>
         <el-form-item label="班级">
            <el-checkbox-group v-model="adTeacherCycl.classId">
               <el-checkbox v-for="item in classData" :key="item.classId" :label="item.className" :value="item.classId"
                  checked>
                  {{ item.className }}
                  <el-time-select v-model="getClassTime(item.classId).testBeginTime" style="width: 200px"
                     :max-time="endTime" class="mr-4" placeholder="开始时间" start="08:30" step="00:15" end="18:30" />
                  <el-time-select v-model="getClassTime(item.classId).testEndTime" style="width: 200px"
                     :min-time="startTime" placeholder="结束时间" start="08:30" step="00:15" end="18:30" />
               </el-checkbox>
            </el-checkbox-group>
         </el-form-item>
         <div style="text-align: right;">
            <el-button type="primary" @click="submitCycl">提交</el-button>
         </div>
      </el-form>
   </el-dialog>
   <!-- 补考 -->
   <el-dialog v-model="diaExamination" title="补考申请" width="430px" style="font-weight: 800;">
      <el-form ref="roleRef2" style="max-width: 600px" :model="formExamination" status-icon label-width="auto"
         class="demo-ruleForm" :rules="rules3">
         <el-form-item label="补考时间" style="width: 400px"
            :rules="{ required: true, message: '考试时间不能为空', trigger: 'blur' }">
            <el-date-picker v-model="ExamTime" value-format="YYYY-MM-DD HH:mm:ss" type="datetimerange"
               range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间">
            </el-date-picker>
         </el-form-item>
         <el-form-item label="补考说明" style="width: 400px" prop="cause">
            <el-input type="textarea" v-model="formExamination.cause" />
         </el-form-item>
         <div style="text-align: right;">
            <el-button type="primary" @click="submitExamination()">
               提交
            </el-button>
         </div>
      </el-form>
   </el-dialog>
   <!-- 驳回弹框 -->
   <el-dialog v-model="dialogVisiblePass" title="驳回" width="430px" style="font-weight: 800;">
      <el-form ref="roleRefExamDuration" style="max-width: 600px" :model="form3" status-icon label-width="auto"
         class="demo-ruleForm" :rules="rules2">
         <el-form-item label="驳回原因" style="width: 400px" prop="backCause">
            <el-input type="textarea" v-model="form3.backCause" clearable />
         </el-form-item>
         <div style="text-align: right;">
            <el-button type="primary" @click="submitback()">
               提交
            </el-button>
         </div>
      </el-form>
   </el-dialog>
   <!-- 驳回原因 -->
   <el-dialog v-model="dialogVisibleBack" title="" width="430px" style="font-weight: 800;">
      <el-form style="max-width: 600px" :model="backCause" status-icon label-width="auto" class="demo-ruleForm">
         <el-form-item label="驳回原因" style="width: 400px">
            <el-input type="textarea" v-model="form3.backCause" :disabled="true" />
         </el-form-item>
      </el-form>
   </el-dialog>
</template>

<script setup>
import {
   adminExaminationList, adminAdminAndTeacherList, adminSubjectList, adminExaminationAdd,
   adminExaminationById, adminExaminationUpdate, adminExaminationDelete, exportOrder,
   adminTestPaperById, getSubjectById, getLevelList, getLevelById,
   getLPById, addExaminationInformationBySelf, getClassList, delQuestion, addQuestion,
   addDailyExams, getExaminationInfoListByTeacherId, passExamination, rejectExamination
} from "@/api/admin/examination/index.js";
import { submitRetakesInfo } from '@/api/admin/retakesInfo/index.js'
import { adminQuestionBySubjectId } from "@/api/admin/subject/index.js";
import { stu_list_tree } from "@/api/admin/student/student_api.js"
import { ref, onMounted, getCurrentInstance, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useUserStore1 } from '../../store/userStore.js'
import { useRouter } from "vue-router";

const router = useRouter()
const user = useUserStore1().userInfo;
const { proxy } = getCurrentInstance();
const roleList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const boo = ref("随机出题")
const title = ref("");
const text1 = ref("");
const text2 = ref("");
const text3 = ref("");
const text4 = ref("");
const options1 = ref([])
const options2 = ref([])
const options3 = ref([])
const options4 = ref([])
const options5 = ref([])
const multipleTable = ref()
const levelId = ref('')
const lpId = ref('')
const optionsQuestion = ref([])
const name = ref('')
const examDuration = ref('')
const dialogVisible = ref(false)
const dialogVisibleXun = ref(false)
const diaExamination = ref(false)
const dialogVisiblePass = ref(false)
const dialogVisibleBack = ref(false)
const flag1 = ref(false)
const flag2 = ref(false)
const flag3 = ref(false)
const flag4 = ref(false)
const ExamTime = ref([])
const tableData = ref([])
const tableData1 = ref([]);
const cacheData = ref([])  //懒加载
const eid = ref(null)
const subId = ref(null)
const qid = ref([])
const bools = ref(false)
const bools1 = ref(true)
const boolsUpdate = ref(true)
//考试随机表单
let form = ref({
   id: '',
   classId: '',
   name: '',
   uid: user.userId,
   subId: '',
   radioCounts: 5,
   checkCounts: 5,
   judgmentCounts: 5,
   textCounts: 5,
   examDuration: '',
   radioScope: 1,
   checkScope: 1,
   judgmentScope: 1,
   textScope: 1,
   beginTime: '',
   endTime: ''
})
//考试选择表单
let form1 = ref({
   id: '',
   classId: '',
   name: '',
   uid: user.userId,
   subId: '',
   radioCounts: [],
   checkCounts: [],
   judgmentCounts: [],
   textCounts: [],
   examDuration: '',
   radioScope: 1,
   checkScope: 1,
   judgmentScope: 1,
   textScope: 1,
   beginTime: '',
   endTime: ''
})
const optionsStatus = [{
   value: '3',
   label: '待审核',
},
{
   value: '4',
   label: '已驳回',
}]
//驳回表单
let form3 = ref({
   id: '',
   backCause: ''
})
//考试选择表单
let formExamination = ref({
   cause: '',
   examinationId: '',
   userId: user.userId,
   retakesBegin: '',
   retakesEnd: ''
})
const rules2 = reactive({
   backCause: [{ required: true, message: '驳回原因不能为空', trigger: 'blur' }],
})
const rules3 = reactive({
   cause: [{ required: true, message: '申请原因不能为空', trigger: 'blur' }],
})
//驳回
function handleReject(row) {
   form3.value.backCause = undefined
   form3.value.id = row.id
   dialogVisiblePass.value = true
}

//驳回提交
function submitback() {
   proxy.$refs["roleRefExamDuration"].validate(valid => {
      if (valid) {
         rejectExamination(form3.value.id, form3.value.backCause).then(res => {
            if (res.data.code == 200) {
               ElMessage.success('驳回成功')
               getList()
               dialogVisiblePass.value = false
            } else {
               ElMessage.success(res.data.message)
               getList()
               dialogVisiblePass.value = false
            }
         })
      }
   })
}
//同意申请
function handleOk(row) {
   passExamination(row.id).then(res => {
      if (res.data.code == 200) {
         ElMessage.success('已同意')
         getList()
      } else {
         ElMessage.success(res.data.message)
         getList()
      }
   })
}
//讲师查看驳回原因
function handleView(row) {
   dialogVisibleBack.value = true
   form3.value.backCause = row.backCause
}
//补考
function handleMakeUp(row) {
   formExamination = ref({
      cause: '',
      examinationId: '',
      userId: user.userId,
      retakesBegin: '',
      retakesEnd: ''
   })
   formExamination.value.examinationId = row.id
   diaExamination.value = true
}
//提交补考信息
function submitExamination() {
   proxy.$refs["roleRef2"].validate(valid => {
      if (valid) {
         if (ExamTime.value.length == 0) {
            ElMessage.error('补考时间不能为空')
         } else {
            formExamination.value.retakesBegin = ExamTime.value[0]
            formExamination.value.retakesEnd = ExamTime.value[1]
            submitRetakesInfo(formExamination.value).then(res => {
               if (res.data.code == 200) {
                  ExamTime.value = []
                  ElMessage.success('提交成功')
                  diaExamination.value = false
                  getList()
               } else {
                  ExamTime.value = []
                  ElMessage.error(res.data.message)
                  diaExamination.value = false
                  getList()
               }
            })
         }
      }
   })

}
//教学周期日考
const teacherCycl = ref(false);
const aaa = []
let adTeacherCycl = ref({
   cycleTime: [],
   classId: [],
   beginEndTime: [], // 存储每个班级的开始时间和结束时间
});
const classData = ref([]);

// 获取班级列表
async function handleTeachingcycle() {
   teacherCycl.value = true;
   const res = await getClassList(); // 假设这是一个异步函数获取班级列表
   classData.value = res.data.obj;
}
// 根据班级ID获取对应的开始时间和结束时间
function getClassTime(classId) {
   if (!aaa[classId]) {
      // 如果还没有初始化，则初始化为默认值
      aaa[classId] = {
         testBeginTime: "15:50",
         testEndTime: "16:35"
      };
   }
   return aaa[classId];
}

// 提交日考表单
function submitCycl() {
   adTeacherCycl.value.beginEndTime = []
   aaa.forEach(arr => {
      if (arr != null) {
         adTeacherCycl.value.beginEndTime.push(arr)
      }
   });
   addDailyExams(adTeacherCycl.value).then(res => {
      if (res.data.code == 200) {
         ElMessage.success('发布成功')
         teacherCycl.value = false
      } else {
         ElMessage.error(res.data.message)
         teacherCycl.value = false
      }
   })
}
//班级动态菜单
stu_list_tree().then(res => {
   cacheData.value = res.data.obj[0].children
})

//动态查询
const queryParams = ref({
   pageNum: 1,
   pageSize: 10,
   classId: '',
   name: '',
   subId: '',
   uid: '',
   beginTime: '',
   endTime: '',
   state: ''
})
//分页
const handleSizeChange = (val) => {
   queryParams.value.pageSize = val
   getList()
}
const handleCurrentChange = (val) => {
   queryParams.value.pageNum = val
   getList()
}
onMounted(() => {
   getList();
   getShow();
   getSelect();
   getLevelShow();
})
const rules = reactive({
   name: [{ required: true, message: '考试名称不能为空', trigger: 'blur' }],
   subId: [{ required: true, message: '课程不能为空', trigger: 'blur' }],
   classId: [{ required: true, message: '班级名称不能为空', trigger: 'blur' }],
})
const rules1 = reactive({
   name: [{ required: true, message: '考试名称不能为空', trigger: 'blur' }],
   subId: [{ required: true, message: '课程不能为空', trigger: 'blur' }],
   classId: [{ required: true, message: '班级名称不能为空', trigger: 'blur' }],
})
//选择题目
function handleXun(index) {
   bools1.value = true
   bools.value = false
   if (form1.value.subId == '') {
      ElMessage.success('请先选择单元')
   } else {
      tableData1.value = []
      dialogVisibleXun.value = true
      tableData.value.forEach(arr => {
         if (arr.typeId == index) {
            tableData1.value.push(arr)
         }
      });
      if (index == 1) {
         var arr1 = []
         if (va.value.radioCounts) {
            va.value.radioCounts.forEach(element => {
               arr1.push(element)
            });
         }
      }
      if (index == 2) {
         var arr2 = []
         if (va.value.checkCounts) {
            va.value.checkCounts.forEach(element => {
               arr2.push(element)
            });
         }
      }
      if (index == 3) {
         var arr3 = []
         if (va.value.judgmentCounts) {
            va.value.judgmentCounts.forEach(element => {
               arr3.push(element)
            });
         }
      }
      if (index == 4) {
         var arr4 = []
         if (va.value.textCounts) {
            va.value.textCounts.forEach(element => {
               arr4.push(element)
            });
         }
      }
      setTimeout(() => {
         if (arr1 != []) {
            toggleSelection(arr1)
         }
         if (arr2 != []) {
            toggleSelection(arr2)
         }
         if (arr3 != []) {
            toggleSelection(arr3)
         }
         if (arr4 != []) {
            toggleSelection(arr4)
         }
      }, 500)
   }
}
const va = ref({})
const handleSelectionChange1 = (val) => {
   qid.value = []
   val.forEach(str => {
      qid.value.push(str.id)
   });

   if (text1.value == '') {
      form1.value.radioCounts = []
      va.value.radioCounts = []
   }
   if (text2.value == '') {
      form1.value.checkCounts = []
      va.value.checkCounts = []
   }
   if (text3.value == '') {
      form1.value.judgmentCounts = []
      va.value.judgmentCounts = []
   }
   if (text4.value == '') {
      form1.value.textCounts = []
      va.value.textCounts = []
   }
   val.forEach(arr => {
      if (arr.typeId == 1) {
         // 判断是否已经存在于 va.value.radioCounts 中，如果不存在才添加
         if (!va.value.radioCounts.some(element => element.id === arr.id)) {
            va.value.radioCounts.push(arr);
            form1.value.radioCounts.push(arr.id);
         }
         // 处理取消选中的情况
         // 如果 val 中的某个元素不在新的选择中，则从相应的数组中移除
         const valIds = val.map(item => item.id);
         va.value.radioCounts = va.value.radioCounts.filter(elem => valIds.includes(elem.id));
         // 更新 form1 中对应的计数数组
         form1.value.radioCounts = va.value.radioCounts.map(elem => elem.id);
      } else if (arr.typeId == 2) {
         // 判断是否已经存在于 va.value.checkCounts 中，如果不存在才添加
         if (!va.value.checkCounts.some(element => element.id === arr.id)) {
            va.value.checkCounts.push(arr);

            form1.value.checkCounts.push(arr.id);
         }
         // 处理取消选中的情况
         // 如果 val 中的某个元素不在新的选择中，则从相应的数组中移除
         const valIds = val.map(item => item.id);
         va.value.checkCounts = va.value.checkCounts.filter(elem => valIds.includes(elem.id));
         // 更新 form1 中对应的计数数组
         form1.value.checkCounts = va.value.checkCounts.map(elem => elem.id);
      } else if (arr.typeId == 3) {
         // 判断是否已经存在于 va.value.judgmentCounts 中，如果不存在才添加
         if (!va.value.judgmentCounts.some(element => element.id === arr.id)) {
            va.value.judgmentCounts.push(arr);
         }
         // 处理取消选中的情况
         // 如果 val 中的某个元素不在新的选择中，则从相应的数组中移除
         const valIds = val.map(item => item.id);
         va.value.judgmentCounts = va.value.judgmentCounts.filter(elem => valIds.includes(elem.id));
         // 更新 form1 中对应的计数数组
         form1.value.judgmentCounts = va.value.judgmentCounts.map(elem => elem.id);
      } else if (arr.typeId == 4) {
         // 判断是否已经存在于 va.value.textCounts 中，如果不存在才添加
         if (!va.value.textCounts.some(element => element.id === arr.id)) {
            va.value.textCounts.push(arr);
            form1.value.textCounts.push(arr.id);
         }
         // 处理取消选中的情况
         // 如果 val 中的某个元素不在新的选择中，则从相应的数组中移除
         const valIds = val.map(item => item.id);
         va.value.textCounts = va.value.textCounts.filter(elem => valIds.includes(elem.id));
         // 更新 form1 中对应的计数数组
         form1.value.textCounts = va.value.textCounts.map(elem => elem.id);
      }
   });
}

const toggleSelection = (rows) => {
   if (rows) {
      rows.forEach(row => {
         multipleTable.value.toggleRowSelection(row)
      });
   }
};

//确定选择
function Add() {
   text1.value = form1.value.radioCounts.length
   text2.value = form1.value.checkCounts.length
   text3.value = form1.value.judgmentCounts.length
   text4.value = form1.value.textCounts.length
   if (text1.value != '') {
      flag1.value = true
   } if (text2.value != '') {
      flag2.value = true
   } if (text3.value != '') {
      flag3.value = true
   } if (text4.value != '') {
      flag4.value = true
   }
   dialogVisibleXun.value = false
}
//查询阶段
function getLevelShow() {
   getLevelList().then(res => {
      options2.value = res.data.obj
   })
}
//根据阶段查询学习阶段
function byId1(id) {
   getLPById(id).then(res => {
      options4.value = res.data.obj
   })
}
//根据学习阶段查询单元
function byId(id) {
   getSubjectById(id).then(res => {
      options3.value = res.data.obj
   })
}
//根据单元查询改单元所有的题目
function byId2(id) {
   adminQuestionBySubjectId(id).then(res => {
      if (res.data.code == 200) {
         tableData.value = res.data.obj
      }
   })
}
/** 查询试卷列表 */
async function getList() {
   if (queryParams.value.subId != '') {
      queryParams.value.subId = queryParams.value.subId[1]
   }
   loading.value = true;
   try {
      if (user.roles.roleName == '管理员') {
         const response = await adminExaminationList(queryParams.value);
         response.data.obj.records.forEach(arr => {
            const index = arr.radioCount.indexOf('_')
            const index1 = arr.checkCount.indexOf('_')
            const index2 = arr.judgmentCount.indexOf('_')
            const index3 = arr.textCount.indexOf('_')
            arr.radioCount = arr.radioCount.slice(0, index);
            arr.checkCount = arr.checkCount.slice(0, index1);
            arr.judgmentCount = arr.judgmentCount.slice(0, index2);
            arr.textCount = arr.textCount.slice(0, index3);

         });
         roleList.value = response.data.obj.records;
         total.value = response.data.obj.total;
         loading.value = false;
      } else {
         const response = await getExaminationInfoListByTeacherId(user.userId, queryParams.value);
         response.data.obj.records.forEach(arr => {
            const index = arr.radioCount.indexOf('_')
            const index1 = arr.checkCount.indexOf('_')
            const index2 = arr.judgmentCount.indexOf('_')
            const index3 = arr.textCount.indexOf('_')
            arr.radioCount = arr.radioCount.slice(0, index);
            arr.checkCount = arr.checkCount.slice(0, index1);
            arr.judgmentCount = arr.judgmentCount.slice(0, index2);
            arr.textCount = arr.textCount.slice(0, index3);
         });
         roleList.value = response.data.obj.records;
         total.value = response.data.obj.total;
         loading.value = false;
      }
   } catch (error) {
      loading.value = false; // Ensure loading state is reset on error
   }
}

const filterTableData = computed(() =>
   roleList.value.filter(
      (data) =>
         !queryParams.value.subjectName ||
         data.subjectName.toLowerCase().includes(queryParams.value.subjectName.toLowerCase()),
   )
)
// 查询课程
function getShow() {
   adminSubjectList().then(res => {
      if (res.data.code == 200) {
         options5.value = res.data.obj
      }
   })
}
//查询发布人
function getSelect() {
   adminAdminAndTeacherList().then(res => {
      if (res.data.code == 200) {
         options1.value = res.data.obj
      }
   })
}
/** 搜索按钮操作 */
function handleQuery() {
   queryParams.value.pageNum = 1;
   getList();
}
/** 重置按钮操作 */
function resetQuery() {
   queryParams.value.name = '';
   queryParams.value.subId = '';
   queryParams.value.uid = '';
   queryParams.value.beginTime = '';
   queryParams.value.endTime = '';
   queryParams.value.classId = '';
   queryParams.value.state = '';
   handleQuery();
}
/** 删除按钮操作 */
function handleDelete(row) {
   if (ids.value.length > 0) {
      adminExaminationDelete(ids.value).then(res => {
         if (res.data.code == 200) {
            getList()
            ElMessage.success('删除成功')
         } else {
            getList()
            ElMessage.error(res.data.message)
         }
      })
   } else {
      ids.value.push(row.id)
      ElMessageBox.confirm(
         '您确认要删除试卷编号为' + row.id + '的数据项?',
         '温馨提示',
         {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
         }).then(() => {
            adminExaminationDelete(ids.value).then(res => {
               if (res.data.code == 200) {
                  ElMessage.success('删除成功')
                  getList()
                  ids.value = []
               } else {
                  getList()
                  ElMessage.error(res.data.message)
               }
            })
         })
         .catch(() => {
            ElMessage({
               type: 'info',
               message: '已取消删除',
            })
         })
   }
}
//删除试卷中的题目
function subjectDelete(id) {
   ElMessageBox.confirm(
      '您确认要删除该题嘛?',
      '温馨提示',
      {
         confirmButtonText: '确认',
         cancelButtonText: '取消',
         type: 'warning',
      }).then(() => {
         delQuestion(id, eid.value).then(res => {
            if (res.data.code == 200) {
               adminTestPaperById(eid.value).then(res => {
                  if (res.data.code == 200) {
                     optionsQuestion.value = res.data.obj
                  }
               })
               ElMessage.success("删除成功");
            } else {
               ElMessage.error("删除失败");
            }
         })
      })
      .catch(() => {
         ElMessage({
            type: 'info',
            message: '已取消删除',
         })
      })
}
//添加题目
function subjectAdd() {
   tableData1.value = []
   bools.value = true
   bools1.value = false
   dialogVisibleXun.value = true
   adminQuestionBySubjectId(subId.value).then(res => {
      if (res.data.code == 200) {
         res.data.obj.forEach(arr => {
            // 检查值是否已经存在于 optionsQuestion.value 中
            if (!optionsQuestion.value.some(item => item.id === arr.id)) {
               // 如果不存在则添加到 tableData1.value 中
               tableData1.value.push(arr);
            }
         });
      }
   })
}
function addSubject() {
   addQuestion(qid.value, eid.value).then(res => {
      if (res.data.code == 200) {
         ElMessage.success('添加成功')
         adminTestPaperById(eid.value).then(res => {
            if (res.data.code == 200) {
               optionsQuestion.value = res.data.obj
            }
         })
         dialogVisibleXun.value = false
      } else {
         ElMessage.error(res.data.message)
      }
   })
}
/** 导出按钮操作 */
function handleExport() {
   exportOrder().then(res => {
      const xlsx = "application/vnd.ms-excel";
      const blob = new Blob([res.data], { type: xlsx });
      const a = document.createElement("a");
      let fileName = "考试信息" + new Date().getTime() + ".xlsx";
      a.download = fileName;
      a.href = window.URL.createObjectURL(blob)
      a.click()
      a.remove()
   });
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
   single.value = selection.length != 1;
   multiple.value = !selection.length;
   ids.value = [];
   selection.forEach(arr => {
      ids.value.push(arr.id)
      if (arr.state == 1) {
         multiple.value = true
         single.value = true
      }
   });
}

/** 重置新增的表单以及其他数据  */
function reset() {
   levelId.value = ''
   lpId.value = ''
   form = ref({
      id: '',
      classId: '',
      name: '',
      uid: user.userId,
      subId: '',
      radioCounts: 5,
      checkCounts: 5,
      judgmentCounts: 5,
      textCounts: 5,
      examDuration: '',
      radioScope: 1,
      checkScope: 1,
      judgmentScope: 1,
      textScope: 1,
      beginTime: '',
      endTime: ''
   })
   form1 = ref({
      id: '',
      classId: '',
      name: '',
      uid: user.userId,
      subId: '',
      radioCounts: [],
      checkCounts: [],
      judgmentCounts: [],
      textCounts: [],
      examDuration: '',
      radioScope: 1,
      checkScope: 1,
      judgmentScope: 1,
      textScope: 1,
      beginTime: '',
      endTime: ''
   })
   ExamTime.value = []
}
/** 发布考试 */
function handleAdd() {
   boolsUpdate.value = true
   reset()
   open.value = true;
   title.value = "发布考试";
}
/** 修改考试信息 */
function handleUpdate(row) {
   boolsUpdate.value = false
   const Id = ref(row.id);
   const id = ref(0);
   ids.value.forEach(arr => {
      id.value = arr
   });
   if (id.value != 0) {
      Id.value = id.value
   }
   reset();
   adminExaminationById(Id.value).then(response => {
      form.value.id = response.data.obj.id
      form.value.name = response.data.obj.name
      form.value.subId = response.data.obj.subId
      getLevelById(response.data.obj.subId).then(res => {
         levelId.value = res.data.obj.levelId
         lpId.value = res.data.obj.lpId
         byId1(levelId.value)
         byId(lpId.value)
      })
      ExamTime.value.push(response.data.obj.beginTime, response.data.obj.endTime)
      form.value.classId = response.data.obj.classId
      // 分割单选题字符串
      let parts = response.data.obj.radioCount.split('_');
      // 去除''
      let cleanedRadioCount = parts[0].replace('', '');
      let cleanedRadioScope = parts[1].replace('', '');
      //回显单选题和单选分数
      form.value.radioCounts = cleanedRadioCount
      form.value.radioScope = cleanedRadioScope
      // 分割多选题字符串
      let parts1 = response.data.obj.checkCount.split('_');
      // 去除''
      let cleanedCheckCount = parts1[0].replace('', '');
      let cleanedCheckScope = parts1[1].replace('', '');
      //回显单选题和单选分数
      form.value.checkCounts = cleanedCheckCount
      form.value.checkScope = cleanedCheckScope
      // 分割判断题字符串
      let parts2 = response.data.obj.judgmentCount.split('_');
      // 去除''
      let cleanedJudgmentCount = parts2[0].replace('', '');
      let cleanedJudgmentScope = parts2[1].replace('', '');
      //回显单选题和单选分数
      form.value.judgmentCounts = cleanedJudgmentCount
      form.value.judgmentScope = cleanedJudgmentScope
      // 分割简单题字符串
      let parts3 = response.data.obj.textCount.split('_');
      // 去除''
      let cleanedTextCount = parts3[0].replace('', '');
      let cleanedTextScope = parts3[1].replace('', '');
      //回显单选题和单选分数
      form.value.textCounts = cleanedTextCount
      form.value.textScope = cleanedTextScope
      open.value = true;
      title.value = "修改考试信息";
   });
}

/** 提交按钮 */
function submitForm() {
   proxy.$refs["roleRef"].validate(valid => {
      if (valid) {
         if (ExamTime.value.length > 0) {
            form.value.beginTime = ExamTime.value[0]
            form.value.endTime = ExamTime.value[1]
            const timestamp1 = new Date(form.value.beginTime).getTime();
            const timestamp2 = new Date(form.value.endTime).getTime();
            const aa = (timestamp2 - timestamp1) / 1000
            const hours = Math.floor(aa / 3600);
            const minutes = Math.floor((aa % 3600) / 60);
            const seconds = aa % 60;
            // 使用padStart确保每个部分至少两位数
            const formattedHours = hours.toString().padStart(2, '0');
            const formattedMinutes = minutes.toString().padStart(2, '0');
            const formattedSeconds = seconds.toString().padStart(2, '0');
            form.value.examDuration = `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
            if (form.value.id != '') {
               adminExaminationUpdate(form.value).then(response => {
                  ElMessage.success("修改成功");
                  open.value = false;
                  getList();
               });
            } else {
               adminExaminationAdd(form.value).then(response => {
                  if (response.data.code == 200) {
                     ElMessage.success("新增成功");
                     open.value = false;
                     getList();
                  } else {
                     ElMessage.error(response.data.message)
                     open.value = false;
                     getList();
                  }
               });
            }
         } else {
            ElMessage.error('考试时间不能为空')
         }
      }
   });
}
/** 取消按钮 */
function cancel() {
   open.value = false;
   reset();
}
/** 提交按钮 */
function submitForm1() {
   proxy.$refs["roleRef1"].validate(valid => {
      if (valid) {
         if (ExamTime.value.length > 0) {
            form1.value.beginTime = ExamTime.value[0]
            form1.value.endTime = ExamTime.value[1]
            const timestamp1 = new Date(form1.value.beginTime).getTime();
            const timestamp2 = new Date(form1.value.endTime).getTime();
            const aa = (timestamp2 - timestamp1) / 1000
            const hours = Math.floor(aa / 3600);
            const minutes = Math.floor((aa % 3600) / 60);
            const seconds = aa % 60;
            // 使用padStart确保每个部分至少两位数
            const formattedHours = hours.toString().padStart(2, '0');
            const formattedMinutes = minutes.toString().padStart(2, '0');
            const formattedSeconds = seconds.toString().padStart(2, '0');
            form1.value.examDuration = `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
            addExaminationInformationBySelf(form1.value).then(response => {
               if (response.data.code == 200) {
                  ElMessage.success("新增成功");
                  open.value = false;
                  open.value = false;
                  levelId.value = ''
                  lpId.value = ''
                  getList();
               } else {
                  ElMessage.error(response.data.message)
                  open.value = false;
                  getList();
               }
            });
         } else {
            ElMessage.error('考试时间不能为空')
         }
      }
   })
}
/** 取消按钮 */
function cancel1() {
   open.value = false;
   levelId.value = ''
   lpId.value = ''
   form1 = ref({
      id: '',
      classId: '',
      name: '',
      uid: user.userId,
      subId: '',
      radioCounts: [],
      checkCounts: [],
      judgmentCounts: [],
      textCounts: [],
      examDuration: '',
      radioScope: 1,
      checkScope: 1,
      judgmentScope: 1,
      textScope: 1,
      beginTime: '',
      endTime: ''
   })
   ExamTime.value = []
}
const obj = ref(null)
// 根据课程id查找对应的题目信息
function handleAuthUser(row) {
   obj.value = row
   eid.value = row.id
   subId.value = row.subId
   dialogVisible.value = true
   name.value = row.name
   examDuration.value = row.examDuration
   adminTestPaperById(row.id).then(res => {
      if (res.data.code == 200) {
         optionsQuestion.value = res.data.obj
      }
   })
}
const getColor = (text, i) => {
   var boo = false
   text.split("").forEach(element => {
      if (element == "A" && i == 0 || element == "B" && i == 1 || element == "C" && i == 2 || element == "D" && i == 3) {
         boo = true
      }
   });
   return boo
}
const props = defineProps({
   /* 是否显示检索条件 */
   showSearch: {
      type: Boolean,
      default: true,
   },
   /* 显隐列信息 */
   columns: {
      type: Array,
   },
   /* 是否显示检索图标 */
   search: {
      type: Boolean,
      default: true,
   },
   /* 显隐列类型（transfer穿梭框、checkbox复选框） */
   showColumnsType: {
      type: String,
      default: "checkbox",
   },
   /* 右外边距 */
   gutter: {
      type: Number,
      default: 10,
   },
})

const emits = defineEmits(['update:showSearch', 'queryTable']);

// 搜索
function toggleSearch() {
   if (showSearch.value == true) {
      showSearch.value = false
   } else {
      showSearch.value = true
   }
   emits("update:showSearch", !props.showSearch);
}

// 刷新
function refresh() {
   getList()
}

</script>
<style>
.avatar-uploader .el-upload {
   border: 1px dashed var(--el-border-color);
   border-radius: 6px;
   cursor: pointer;
   position: relative;
   overflow: hidden;
   transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
   border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
   font-size: 28px;
   color: #8c939d;
   width: 178px;
   height: 178px;
   text-align: center;
}

/* main-container全局样式 */
.app-container {
   padding: 20px;
}

label {
   font-weight: 700;
}

.icon-large-button .el-icon {
   font-size: 100px;
}
</style>